package book.ch9;


import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

class MousePolice implements MouseListener {
    WindowMouse view;
    public void setView(WindowMouse view) {
        this.view = view;
    }
    public void mousePressed(MouseEvent e) {
        if(e.getSource() == view.button&&e.getButton() == MouseEvent.BUTTON1) {
            view.area.append("在按钮上按下鼠标左键:\n");
            view.area.append(e.getX()+","+e.getY()+"\n");
        }
        else if(e.getSource() == view&&e.getButton() == MouseEvent.BUTTON1) {
            view.area.append("在窗体中按下鼠标左键:\n");
            view.area.append(e.getX()+","+e.getY()+"\n");
        }
    }
    public void mouseReleased(MouseEvent e) {}
    public void mouseEntered(MouseEvent e)  {
        if(e.getSource() instanceof JButton)
            view.area.append("\n鼠标进入按纽,位置:"+e.getX()+","+e.getY()+"\n");
        if(e.getSource() instanceof JFrame)
            view.area.append("\n鼠标进入窗口,位置:"+e.getX()+","+e.getY()+"\n");
    }
    public void mouseExited(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {
        if(e.getClickCount()>=2)
            view.area.setText("鼠标连击\n");
    }
}


class WindowMouse extends JFrame {
    JButton button;
    JTextArea area;
    MousePolice police;
    WindowMouse() {
        init();
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
    void init() {
        setLayout(new FlowLayout());
        area = new JTextArea(10,28);
        Font font = new Font("宋体",Font.PLAIN,22);
        area.setFont(font);
        police = new MousePolice();
        police.setView(this);//将当前窗口传递给police组合的窗口
        button = new JButton("按钮");
        button.addMouseListener(police);
        addMouseListener(police);
        add(button);
        add(new JScrollPane(area));
    }
}

public class E9_10 {
    public static void main(String[] args) {
        WindowMouse win=new WindowMouse();
        win.setTitle("处理鼠标事件");
        win.setBounds(10,10,560,380);
    }
}
